<template>
  <div>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon
      hide-required-asterisk="false">
      <el-form-item label="知识标题" prop="title">
        <el-input v-model="ruleForm.title" placeholder="请输入标题"></el-input>
      </el-form-item>
      <el-form-item label="知识类型" prop="type">
        <el-radio-group v-model="ruleForm.type">
          <el-radio :label="0" value="0">血糖</el-radio>
          <el-radio :label="1" value="1">饮食</el-radio>
          <el-radio :label="2" value="2">其他</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="浏览量" prop="views">
        <el-input-number v-model="ruleForm.views" width="800px" placeholder="请输入浏览量"  :step="1" :step-strictly="true"
          min="1" controls-position="right" style="width: 300px;" @keydown="handleKeyDown"/>
      </el-form-item>
      <el-form-item label="知识权重" prop="weight">
        <el-input-number v-model="ruleForm.weight" width="800px" placeholder="请输入知识权重"  :step="1" :step-strictly="true"
          min="1" controls-position="right" style="width: 300px;"  @keydown="handleKeyDown"/>
      </el-form-item>
      <el-form-item label="选择封面图片" height="40">
        <el-upload :multiple="false" accept=".jpg,.jpeg,.png"  :show-file-list="true"
          list-type="picture-card" @change="handelFileChange"  :auto-upload="false">
          <el-image class="avatar" v-if="imageUrl" :src="imageUrl" />
          <el-icon v-else>
            <Plus />
          </el-icon>
          <template #tip>
            <div class="el-upload__tip">jpg/png格式图片且图片大小不能超过500kb</div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="知识摘要" prop="summary">
        <el-input type="textarea" rows="6" v-model="ruleForm.summary" placeholder="请输入摘要" maxlength="120"
          show-word-limit="true"></el-input>
      </el-form-item>

      <el-form-item label="知识内容">
        <div style="border: 1px solid #ccc">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
            :mode="mode" />
          <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="handleCreated" />
        </div>
      </el-form-item>

    </el-form>

    <span class="dialog-footer">
      <el-button type="primary" @click="submitForm(ruleFormRef)">新增</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置表单</el-button>
      <el-button @click="handleReturn">返回</el-button>
    </span>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import request from '../../utils/request'
import { ElNotification } from 'element-plus'
import { useRouter } from 'vue-router'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
export default {
  components: { Editor, Toolbar },
  setup() {
    const router = useRouter()

    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()
    const handleImage = () => {
    }
    // 内容 HTML
    const valueHtml = ref()
    const toolbarConfig = {}
    const editorConfig = { MENU_CONF: {} }
    editorConfig.MENU_CONF['uploadImage'] = {
      // 自定义上传
      async customUpload(file, insertFn) {  // TS 语法
        let formdata = new FormData()
        formdata.append('files', file)
        const url = ref("")
        request
          .request({
            url: '/knowledge/imageAdd',
            method: 'post',
            data: formdata,
            headers: { 'Content-Type': 'multipart/form-data' }
          })
          .then((res) => {
            if (res.data.code == 200) {
              ElNotification({
                title: '图片上传成功',
                message: '图片上传成功',
              })
              url.value = res.data.data.payload[0]
              insertFn(url.value)
              // const paths = res.data.data.payload
            } else if (res.data.data.code == 0) {
              ElNotification({
                title: '图片上传失败',
                message: '图片过大,请重新选择图片',
              })
            } 
          })
      },
      // 上传错误，或者触发 timeout 超时
      onError(file, err, res) {  // TS 语法
        // onError(file, err, res) {               // JS 语法
        console.log(`${file.name} 上传出错`, err, res)
      },
    }
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const checkRePassword = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }

    const rules = reactive({
      title: [
        {
          required: true,
          message: '请输入知识标题',
          trigger: 'blur',
        },
      ],

      content: [
        {
          required: true,
          message: '请输入知识内容',
          trigger: 'blur',
        },
      ],
      type: [
        {
          required: true,
          message: '请选择知识类型',
          trigger: 'change',
        },
      ],
      image: [
        {
          required: true,
          message: '请选择文件',
          trigger: 'change',
        },
      ],
      views: [
        {
          required: true,
          message: '请输入浏览量',
          trigger: 'blur',
        },
        { validator: checkRePassword, message: '不能输入负数' }
      ],
      weight: [
        {
          required: true,
          message: '请输入知识权重',
          trigger: 'blur',
        },
        { validator: checkRePassword, message: '不能输入负数' }
      ],
      summary: [
        {
          required: true,
          message: '请输入知识摘要',
          trigger: 'blur',
        },
        // { validator: checkRePassword, message: '不能输入负数' }
      ]
    })

    const ruleFormRef = ref({})
    const ruleForm = ref({
      type: 0,
      views: 1,
      weight: 1
    })
    const selectedFile = ref(null)

    // 重置表单
    const resetForm = (formEl) => {
      valueHtml.value = ""
      imageUrl.value = ""
      // searchRecipeName.value = ""
      // ruleForm.value.foods = []
      // ruleFormRef.value = ""
      formEl.resetFields()
    }

    // 获取文件数据
    const imageUrl = ref('')
    const handelFileChange = (file) => {
      const isLt500k = file.raw.size / 1024 < 500
      if (!isLt500k) {
        ElNotification({
          title: '图片过大',
          message: '图片不能超过500k',
        })
        return
      }
      selectedFile.value = file.raw
      imageUrl.value = URL.createObjectURL(file.raw)
    }
    // 处理添加方法的参数数据
    const processFormData = () => {
      const formData = new FormData()
      formData.append('title', ruleForm.value.title)
      formData.append('summary', ruleForm.value.summary)
      formData.append('content', valueHtml.value)
      formData.append('type', ruleForm.value.type)
      formData.append('views', ruleForm.value.views)
      formData.append('weight', ruleForm.value.weight)
      if (selectedFile.value) {
        const fileName = selectedFile.value.name
        formData.append('avator', selectedFile.value, fileName)
      }
      return formData
    }

    // 提交表单
    const submitForm = async (ruleFormRef) => {
      const formData = processFormData()
      if (!ruleFormRef) return
      await ruleFormRef.validate((valid, fields) => {
        if (!valid) {
          ElNotification({
            title: '添加失败',
            message: '请完善知识信息',
          })
          return
        } else if (!selectedFile.value) {
          ElNotification({
            title: '添加失败',
            message: '请添加封面图',
          })
          return
        } else if (valueHtml.value == '<p><br></p>') {
          ElNotification({
            title: '添加失败',
            message: '请添加知识内容',
          })
          return
        }
        if (valid) {
          request
            .request({
              url: '/knowledge/add',
              method: 'post',
              data: formData
            })
            .then((res) => {
              if (res.data.code == 200) {
                ElNotification({
                  title: '添加成功',
                  message: '成功添加知识信息',
                })
                router.push('/knowledge')
              } else {
                ElNotification({
                  title: '添加失败',
                  message: '请联系管理员检查失败原因',
                })
              }
            })
            .catch((e) => {
              console.log(1111111,e)
              ElNotification({
                title: '添加失败',
                message: '请联系管理员检查失败原因',
              })
            })
        } else {
          ElNotification({
            title: '校验失败',
            message: '请重新填写信息',
          })
        }
      })
    }
    // 禁止输入e
    const handleKeyDown = (event) => {
      if (event.key === 'e') {
        event.preventDefault()
      }
    }
    // 返回页面函数 
    const handleReturn = () => {
      router.push('/knowledge')
    }
    return {
      ruleForm,
      ruleFormRef,
      rules,
      // md,
      imageUrl,
      handelFileChange,
      submitForm,
      resetForm,
      handleKeyDown,
      editorRef,
      valueHtml,
      mode: 'default',
      toolbarConfig,
      editorConfig,
      handleCreated,
      handleImage,
      handleReturn
    }
  },
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 100%;
  height: 100%;
}
</style>

<style>
.el-upload--text {
  height: auto;
  width: auto;
}

.mavonEditor {
  width: 100%;
  height: 100%;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-upload-list__item.is-ready,
.el-upload-list__item.is-uploading {
  display: none !important;
}
</style>
